package com.ucode.hrm.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.hrm.service.HrmCustomerCompanyService;
import com.ucode.hrm.service.HrmCustomerProjectService;
import com.ucode.hrm.service.HrmJobPostService;
import com.ucode.model.hrm.HrmCustomerCompany;
import com.ucode.model.hrm.HrmCustomerProject;
import com.ucode.model.hrm.HrmJobPost;
import com.ucode.model.hrm.convert.HrmJobPostConvert;
import com.ucode.model.hrm.form.HrmJobPostForm;
import com.ucode.model.hrm.vo.HrmJobPostVO;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.util.IdentifyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.*;

@Tag(name = "管理后台 - 人力资源系统 - 招聘岗位")
@RestController
@RequestMapping("/hrm/job-post")
@Validated
public class HrmJobPostController {

    @Resource
    private HrmJobPostService jobPostService;
    @Resource
    private HrmCustomerProjectService customerProjectService;
    @Resource
    private HrmCustomerCompanyService  customerCompanyService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:job-post:query')")
    public ResponseResult<Paginator<HrmJobPostVO>> pageList(
            @Schema(description = "客户项目编码") @RequestParam(value = "customerProjectId",required = false) Long customerProjectId,
            @Schema(description = "标题") @RequestParam(value = "title",required = false) String title,
            @Schema(description = "公司名称") @RequestParam(value = "companyName",required = false) String companyName,
            @Schema(description = "职位类型") @RequestParam(value = "jobType",required = false) Integer jobType,
            @Schema(description = "职位状态") @RequestParam(value = "status",required = false) Integer status,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(title))
            condition.put("title", StrUtil.concat(true,"%", title,"%"));
        if(StrUtil.isNotBlank(companyName))
            condition.put("companyName", StrUtil.concat(true,"%", companyName,"%"));


        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("customerProjectId",customerProjectId);
        condition.put("jobType",jobType);
        condition.put("status",status);
        condition.put("deltag",false);
        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    private Paginator<HrmJobPostVO> pageList(Map<String,Object> condition, int pageNum, int pageSize) {

        Paginator<HrmJobPost> paginator = jobPostService.queryPageForList(condition,pageSize,pageNum);
        Paginator<HrmJobPostVO> paginatorVO =  HrmJobPostConvert.INSTANCE.convertPage(paginator);

        if(CollUtil.isNotEmpty(paginatorVO.getList())) {
            Set<Long> customerCompanyIds = new HashSet<>();
            Set<Long> customerProjectIds = new HashSet<>();

            for(HrmJobPostVO vo : paginatorVO.getList()){
                if(ObjUtil.isNotNull(vo.getCustomerCompanyId()))
                    customerCompanyIds.add(vo.getCustomerCompanyId());

                if(ObjUtil.isNotNull(vo.getCustomerProjectId()))
                    customerProjectIds.add(vo.getCustomerProjectId());
            }

            Map<Long, HrmCustomerCompany> customerCompanyMap = customerCompanyService.getMap(customerCompanyIds);
            Map<Long, HrmCustomerProject> customerProjectMap = customerProjectService.getMap(customerProjectIds);

            paginatorVO.getList().forEach(item -> {

                if(ObjUtil.isNotNull(item.getCustomerCompanyId())) {
                    HrmCustomerCompany customerCompany = customerCompanyMap.get(item.getCustomerCompanyId());
                    if(customerCompany != null)
                        item.setCompanyName(customerCompany.getCompanyName());
                }

                if(ObjUtil.isNotNull(item.getCustomerProjectId())){
                    HrmCustomerProject customerProject = customerProjectMap.get(item.getCustomerProjectId());
                    if(customerProject != null)
                        item.setProjectName(customerProject.getProjectName());
                }


            });
        }

        return paginatorVO;
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('hrm:job-post:query')")
    public ResponseResult<HrmJobPostVO> getById(@PathVariable(name="id",required=true) Long id){

        HrmJobPost bean = jobPostService.validate(id);
        HrmJobPostVO  vo = HrmJobPostConvert.INSTANCE.convert(bean);


        if(ObjUtil.isNotNull(vo.getCustomerCompanyId())) {
            HrmCustomerCompany customerCompany = customerCompanyService.selectByPrimaryKey(bean.getCustomerCompanyId());
            if(customerCompany != null)
                vo.setCompanyName(customerCompany.getCompanyName());
        }

        if(ObjUtil.isNotNull(vo.getCustomerProjectId())){
            HrmCustomerProject customerProject = customerProjectService.selectByPrimaryKey(vo.getCustomerProjectId());
            if(customerProject != null)
                vo.setProjectName(customerProject.getProjectName());
        }

        return ResponseResult.success(vo);
    }

    @PostMapping("/create")
    @Operation(summary = "创建")
    @PreAuthorize("@usfs.hasPermission('hrm:job-post:create')")
    public ResponseResult<Long> create(@Valid @RequestBody HrmJobPostForm form) {

        HrmJobPost bean = HrmJobPostConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());

        if(ObjUtil.isNotNull(form.getProjectId()) && !ObjUtil.equals(form.getProjectId(),0L)) {
            HrmCustomerProject customerProject = customerProjectService.selectByPrimaryKey(form.getProjectId());
            if(customerProject != null){
                bean.setCustomerCompanyId(customerProject.getCustomerCompanyId());
                bean.setCustomerProjectId(customerProject.getId());
            }
        }

        Long id = jobPostService.insert(bean);
        return ResponseResult.success(id) ;
    }

    @PostMapping("/update/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "修改")
    @PreAuthorize("@usfs.hasPermission('hrm:job-post:update')")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
                                         @Valid @RequestBody HrmJobPostForm form) {
        HrmJobPost bean = HrmJobPostConvert.INSTANCE.convert(form);
        bean.setId(id);

        if(ObjUtil.isNotNull(form.getProjectId()) && !ObjUtil.equals(form.getProjectId(),0L)) {
            HrmCustomerProject customerProject = customerProjectService.selectByPrimaryKey(form.getProjectId());
            if(customerProject != null){
                bean.setCustomerCompanyId(customerProject.getCustomerCompanyId());
                bean.setCustomerProjectId(customerProject.getId());
            }
        }

        int i = jobPostService.update(bean);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('hrm:job-post:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id",required=true) Long id) {
        //逻辑删除
        int i = customerProjectService.logicDeletePrimaryKey(id);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('hrm:job-post:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-100条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids) {
        int i = customerProjectService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

}
